<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>注册</title>
    <link rel="stylesheet" href="./css/login.css">
    <style>
        .showmsg {
            width: 200px;
            height: 100px;
            border-radius: 5px;
            background-color: hotpink;
            position: fixed;
            left: calc(50% - 100px);
            top: calc(50% - 50px);
            display: none;
        }
    </style>
</head>

<body>
    <form id="myform">
        <img src="./images/login.jpg" alt="">
        <input name="username" type=" text" placeholder="请输入用户名">
        <input name="nickname" type="text" placeholder="请输入昵称">
        <input name="password" type=" text" placeholder="请输入密码">
        <input name="password2" type=" text" placeholder="请确认密码">
        <div><button>注册</button><button>返回</button></div>
    </form>
    <div class="showmsg"></div>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script>
    <script>
        var myform = document.querySelector('#myform')
        var bnt = document.querySelectorAll('button')
        var showmsg =document.querySelector('.showmsg')
        function showHh(text) {
            showmsg.style.display = 'block'
            showmsg.innerHTML = text
            setTimeout(function () {
                showmsg.style.display = 'none'
            }, 3000)
        }
        bnt[1].onclick = function (e) {
            e.preventDefault()
            location.href = 'login.html'
            console.log(111);
        }
        bnt[0].onclick = function (e) {
            var username = document.querySelector('input[name=username]').value
            var password = document.querySelector('input[name=password]').value
            var password2 = document.querySelector('input[name=password2]').value
            var nickname = document.querySelector('input[name=nickname]').value
            //阻止默认事件
            //preventDefault()[dom标准写法(ie678不兼容)]
            //ie678用returnValue
            //或者利用return false也能阻止默认行为,没有兼容问题(只限传统注册方式)
            e.preventDefault();
            if (password == password2) {
                $.ajax({
                    url: 'reg',
                    type: 'post',
                    dataType: 'json',
                    data: `username=${username}&password=${password}&nickname=${nickname}`,
                    success(res) {
                        if (res.code == 0) {
                            location.href = 'login.html'
                        } else {
                            showHh(res.msg)
                        }
                    }
                })
            } else {
                alert('前后密码不一致！')
            }

        }
    </script>
</body>

</html>